#include <stdio.h>
#include <emscripten/html5.h>
#include <emscripten.h>
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <cassert>

void alert(const char * msg){
	EM_ASM({
		var msg = UTF8ToString($0);
		alert(msg);
	}, msg);
}

void render()
{
	glClearColor(1.0f, 0.5f, 0.5f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);
}

EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context;

const char * beforeunload(int eventType, const void *reserved, void *userData){
	// alert("beforeunload \n");
	emscripten_cancel_main_loop();
	emscripten_webgl_destroy_context(context);
	return nullptr;
}

int main()
{
	auto result = emscripten_set_beforeunload_callback(nullptr, beforeunload);
	assert(result == EMSCRIPTEN_RESULT_SUCCESS);

	EM_ASM({
		var c = document.createElement("canvas");
		c.id = "canvas2";
		c.style = "width:600px;height:800px";
		document.body.appendChild(c);
	});

	EmscriptenWebGLContextAttributes attribs;
	emscripten_webgl_init_context_attributes(&attribs);
	attribs.alpha = false;
	attribs.enableExtensionsByDefault = false;
	attribs.preserveDrawingBuffer = true;		// 告诉 浏览器 swapbuffers 时 是 "拷贝" 而不是 "交换"

	context = emscripten_webgl_create_context("#canvas2", &attribs);
	printf("%d\n", context);
	emscripten_webgl_make_context_current(context);
	emscripten_set_main_loop(render, 0, true);

	// alert("main loop exit\n");
	// emscripten_webgl_destroy_context(context);

	return 0;
}


